package com.alogic.swagger.core;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;

/**
 * 输出为yaml
 *
 * @since 1.6.13.7 [20200812 duanyy] <br>
 */
public class SwaggerYaml extends AbstractLogiclet {
    protected String $id = "$swagger";

    protected static ThreadLocal<Yaml> yamlLocal = new ThreadLocal<Yaml>(){
        protected Yaml initialValue() {
            return new Yaml();
        };
    };
    public SwaggerYaml(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $id = PropertiesConstants.getRaw(p,"id","");
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
        String id = PropertiesConstants.transform(ctx,$id,"$swagger");
        if (StringUtils.isNotEmpty(id)){
            Yaml yaml = yamlLocal.get();
            ctx.SetValue(id,yaml.dump(current.getContent()));
        }
    }
}
